﻿using MediatR;
using NPOI.SS.Formula.Functions;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.BasicInformation.warehouses;
using THE_WIND_RISES.Common.Dtos;

namespace Enterprise_Set.API.Application.Commands.Week1.Warehouse_CRUD
{
    /// <summary>
    /// 显示仓库表数据
    /// </summary>
    public class SelWarehouseHandler : IRequestHandler<SelWarehouseCommand, Result>
    {
        public SelWarehouseHandler(IBaseRepository<Warehouse> warehouseRepository)
        {
            WarehouseRepository = warehouseRepository;
        }

        public IBaseRepository<Warehouse> WarehouseRepository { get; set; }
        public async Task<Result> Handle(SelWarehouseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CommonErrorCodes.Search };
                var sql = "select * from Warehouse";
                if (request.WarehouseIsDel > 0 || !string.IsNullOrEmpty(request.WarehouseName))
                {
                    sql += " where";
                    if (request.WarehouseIsDel == 1)
                    {
                        sql += " WarehouseState=false";
                        if (request.WarehouseName != "")
                        {
                            sql += " and WarehouseName like(@WarehouseName);";
                        }
                    }
                    else if (request.WarehouseIsDel == 2)
                    {
                        sql += " WarehouseState=true";
                        if (request.WarehouseName != "")
                        {
                            sql += " and WarehouseName like(@WarehouseName);";
                        }
                    }
                    else if (request.WarehouseName != "")
                    {
                        sql += " WarehouseName like(@WarehouseName);";
                    }
                }
                var list = WarehouseRepository.GetAll(sql, new { WarehouseName = ('%' + request.WarehouseName + '%') });
                if (list != null)
                {
                    var count = list.Count();
                    var znum = Convert.ToInt32(Math.Ceiling((double)count / request.qnum));
                    list = list.OrderBy(x => x.WarehouseId).Skip((request.ynum - 1) * request.qnum).Take(request.qnum).ToList();
                    result.Data = new { data = list, count = count, znum = znum };
                    result.Code = (int)CommonErrorCodes.Success;
                    return result;
                }
                else
                {
                    return result;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
